<template>
  <div>
    <Card>
      <div class="handle-area">
        <div class="handle-area-left">
          <Button @click="onCreate" class="search-btn handle-area-left-btn" type="primary"><Icon type="search"/>新增</Button>
          <Button @click="toggleFolder" type="text" class="search-btn handle-area-left-btn">展开-收起</Button>
        </div>
      </div>
      <tree-table
      expand-key="deptName"
      :expand-type="false"
      :selectable="false"
      :columns="columns"
      :is-fold="foldStatus"
      :data="tableData"
      @radio-click="onRowClick"
      >
        <template slot="likes" slot-scope="scope">
          <Button @click="onUpdate(scope)">编辑</Button>&nbsp;
          <Poptip
          confirm
          title="确定删除这条菜单么?"
          @on-ok="handleDelete(scope)"
          >
            <Button>删除</Button>
          </Poptip>&nbsp;
          <!-- <Button @click="showCurrentRow(scope.row)">详情</Button> -->
        </template>
      </tree-table>
    </Card>
    <!-- 新增 或 编辑 -->
      <Drawer
      :title="drawerTitle"
      v-model="onCreateFlag"
      width="720"
      :mask-closable="false"
      :styles="styles"
      >
        <Form ref="formRef" :label-width="80" :model="formData" :rules="ruleValidate">
            <Row :gutter="32">
                <Col span="12">
                    <FormItem label="部门名称" label-position="top" prop="deptName">
                        <Input v-model="formData.deptName" placeholder="请输入" />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="部门编码" label-position="top" prop="code">
                        <Input v-model="formData.code" placeholder="请输入部门编码">
                        </Input>
                    </FormItem>
                </Col>
            </Row>
            <Row :gutter="32">
                <Col span="12">
                    <FormItem label="部门级别" label-position="top" prop="treeLevel">
                      <Select v-model="formData.treeLevel" @on-change="onLevelChange">
                        <Option value="0">一级</Option>
                        <Option value="1">二级</Option>
                        <Option value="2">三级</Option>
                        <Option value="3">四级</Option>
                      </Select>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="父类菜单" label-position="top" prop="parentCode">
                      <Select v-model="formData.parentCode">
                        <Option v-for="menu in parentMenuList" :key="menu.uuid" :value="menu.code">{{ menu.deptName }}</Option>
                      </Select>
                    </FormItem>
                </Col>
            </Row>
            <Row :gutter="32">
                <Col span="12">
                    <FormItem label="排序" label-position="top" prop="treeSort">
                      <Input v-model="formData.treeSort" placeholder="" />
                    </FormItem>
                </Col>
            </Row>
            <FormItem label="描述" label-position="top" prop="description">
                <Input type="textarea" v-model="formData.description" :rows="4" placeholder="请输入个人描述" />
            </FormItem>
        </Form>
        <div class="demo-drawer-footer">
            <Button style="margin-right: 8px" @click="onFormCancle">取消</Button>
            <Button type="primary" v-if="operation === 'create'" @click="doCreate">提交</Button>
            <Button type="primary" v-if="operation === 'edit'" @click="doUpdate">提交</Button>
        </div>
      </Drawer>
  </div>
</template>

<script>
import api from '@/api/base/dept'

export default {
  name: 'tables_page',
  data () {
    return {
      foldStatus: false,
      columns: [
        // { type: 'expand', width: 60, key: 'handle', align: 'center' },
        { title: '部门名称', key: 'deptName', sortable: true, expandable: true },
        { title: '部门编码', key: 'code', sortable: true },
        { title: '创建时间', key: 'createdTime' },
        { title: '更新时间', key: 'updatedTime' },
        {
          title: '操作',
          key: 'handle',
          type: 'template',
          minWidth: '200px',
          template: 'likes'
        }
      ],
      // 三个抽屉变量
      onCreateFlag: false,
      drawerTitle: '',
      operation: 'create',
      tableData: [],
      selectedRows: [],
      currentRow: {},
      showCurrentRowFlag: false,
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      loading: false,
      // 编辑新增
      parentMenuList: [],
      formData: {
        deptName: '',
        code: '',
        menuType: '',
        menuTitle: '',
        permission: '',
        treeLevel: '0',
        isShow: 1,
        description: ''
      },
      ruleValidate: {
        deptName: [
          { required: true, message: 'The deptName cannot be empty', trigger: 'blur' }
        ],
        code: [
          { required: true, message: 'The code cannot be empty', trigger: 'blur' }
        ],
        menuType: [
          { required: true, message: 'The menuType cannot be empty', trigger: 'blur' }
        ],
        menuTitle: [
          { required: true, message: 'menuTitle cannot be empty', trigger: 'blur' }
          // { type: 'email', message: 'Incorrect email format', trigger: 'blur' }
        ],
        permission: [
          { required: true, message: 'The permission cannot be empty', trigger: 'blur' }
        ],
        treeLevel: [
          { required: true, message: 'The treeLevel cannot be empty', trigger: 'blur' }
        ],
        isShow: [
          { required: true, message: 'The isShow cannot be empty', trigger: 'blur' }
        ],
        description: [
          { type: 'string', min: 10, message: 'Introduce no less than 10 words', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    toggleFolder () {
      this.foldStatus = !this.foldStatus
    },
    handleDelete (params) {
      console.log(params)
      const id = params.row.uuid
      this.loading = true
      api.remove(id).then(res => {
        this.loading = false
        this.getData()
      })
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${(new Date()).valueOf()}.csv`
      })
    },
    getData (searchObj) {
      this.loading = true
      api.list(searchObj).then(res => {
        this.arrangeDataToTable(res.data.data)
        this.loading = false
      }).catch(e => {
        console.log(e)
        this.loading = false
      })
    },
    getDataByChangeSize (index) {
      this.page.pageSize = index
      this.getData()
    },
    getDataOnSearch (searchObj) {
      this.page.current = 1
      this.getData(searchObj)
    },
    // 显示当前行数据
    showCurrentRow (row) {
      this.currentRow = row
      this.showCurrentRowFlag = true
    },
    onLevelChange (value) {
      const currentLevel = parseInt(value)
      const parentLevel = currentLevel - 1
      // 大于0 说明可以选父级
      if (parentLevel >= 0) {
        this.getParentMenuList(parentLevel)
      } else {
        this.formData.parentCode = ''
      }
    },
    getParentMenuList (parentLevel) {
      const searchObj = { treeLevel: parentLevel }
      api.all(searchObj).then(res => {
        const data = res.data.data
        this.parentMenuList = data
      })
    },
    // 单行选中
    onSelect (selection, row) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectCancel (selection, row) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectAll (selection) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectAllCancel (selection) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectionChange (selection) {
    },
    onSortChange (column, key, order) {
    },
    onFilterChange (row) {
    },
    onRowClick (row, index) {
      // console.log(row)
    },
    onRowDblclick (row, index) {
      console.log(row)
    },
    onExpand (row, status) {
      console.log(row)
      // this.$emit('on-expand', row, status)
    },
    async onSaveEdit (params) {
      this.loading = true
      const key = params.column.key
      // Object.assign(params.row, { key : params.value})
      this.$set(params.row, key, params.value)
      await api.update(params.row)
      this.loading = false
    },
    onUpdate (selection) {
      console.log(selection)
      this.drawerTitle = '编辑'
      this.operation = 'edit'
      const row = selection.row
      row.treeLevel = row.treeLevel + '' // 转为字符串用来回显
      this.formData = selection.row
      this.onCreateFlag = true
    },
    doUpdate () {
      api.update(this.formData).then(res => {
        if (res.data.code === 200) {
          alert('更新成功!')
          this.resetFormData()
          this.getData()
        }
      })
    },
    onCreate () {
      this.drawerTitle = '新增'
      this.operation = 'create'
      this.onCreateFlag = true
    },
    doCreate () {
      api.add(this.formData).then(res => {
        if (res.data.code === 200) {
          alert('新增成功!')
          this.resetFormData()
          this.getData()
        }
      })
    },
    onFormCancle () {
      this.onCreateFlag = false
      this.resetFormData()
    },
    resetFormData () {
      this.formData = {
        deptName: '',
        code: '',
        menuType: '',
        menuTitle: '',
        permission: '',
        treeLevel: '0',
        isShow: 1,
        description: ''
      }
    },
    // 装配返回数据到页面实体中
    arrangeDataToTable (data) {
      this.tableData = data
    },
    handle (scope) {
      console.log(scope)
    }
  },
  watch: {
    onCreateFlag (val) {
      if (val) {
        this.onLevelChange(this.formData.treeLevel)
      }
    }
  },
  mounted () {
    api.list().then(res => {
      this.arrangeDataToTable(res.data.data)
    })
  }
}
</script>

<style>
.demo-drawer-profile {
    font-size: 14px
}

.demo-drawer-profile .ivu-col {
    margin-bottom: 12px
}

.handle-area {
  padding: 10px 0;
}

</style>
